from .api import default as default_api

import logging

logger = logging.getLogger(__name__)
from .resource import Resource, Create, Find
from .datastructure import Order


class Payment(Find):
    path = '/payment-api/payment'

    # def __init__(self, new_attributes={}, **kwargs):
    #     Resource.__init__(self, new_attributes, kwargs)

        # @classmethod
        # def find(cls, api=None, **kwargs):
        #     _id = kwargs['id']
        #     api = api or default_api()
        #     res = api.get(cls.url, _id, **kwargs)
        #
        #     return cls(**res)


class FundIn(Create):
    url = '/payment-api/fundin/'

    @classmethod
    def _sign(cls, order, api):
        import hashlib
        md5 = hashlib.md5()

        sign_value = '{}{}{}'.format(api.security_code, order.sign_value(), order.payment_time)

        logger.info('Order sign , sign value {}'.format(sign_value))
        md5.update(sign_value.encode())
        return md5.hexdigest()

    @classmethod
    def create(cls, order, api=None):
        logger.debug('Begin fundin payment')
        api = api or default_api()
        data = {}
        if isinstance(order, Order):
            data = order.to_dict()
        elif isinstance(order, dict):
            data.update(order)
            #
            # if hasattr(order, 'sign_value'):
            #     sign_value = getattr(order, 'sign_value')
            #     cls._sign(sign_value, api)

        # sign = cls._sign(order, api)
        # order = {
        #     'amount': float(order.amount),
        #     'fund_channel': order.fund_channel.id,
        #     'payment_time': order.payment_time,
        #     'currency': order.currency,
        #     'merchant': api.client_id,
        #     'sign': sign,
        #     'desc': order.desc or '',
        #     'notify_info': order.notify_info or '',
        #     'trade_code': order.trade_code
        #     # 'return_url': order.return_url,
        # }
        # 2. 发送订单
        logger.info('Send fundin paymnet {}'.format(order))
        res = api.post(cls.url, data=data)
        # 3  解析结果
        return cls(res)
